package com.hb.trade.server.project.section.controller;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hb.core.pojo.enums.SignupStatusEnum;
import com.hb.core.pojo.parent.PageResult;
import com.hb.core.pojo.project.proj.entity.AbstractProject;
import com.hb.core.pojo.project.section.dto.SupplyBidSignupDTO;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.core.pojo.project.section.entity.SupplyBidSignup;
import com.hb.trade.server.project.notice.service.TenderInviteEnterpriseService;
import com.hb.trade.server.project.proj.service.ProjectService;
import com.hb.trade.server.project.section.service.raw.BidSectionService;
import com.hb.trade.server.project.section.service.raw.SupplyBidSignupService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.fzzn.core.model.enums.LogicEnum;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.Enums;
import org.fzzn.core.util.MsgUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 供应商标段报名表 前端控制器
 * </p>
 *
 * @author zhaojk
 * @since 2021-08-30
 */
@RestController
public class SupplyBidSignupController {

    protected final SupplyBidSignupService supplyBidSignupService;
    protected final BidSectionService bidSectionService;
    protected final TenderInviteEnterpriseService tenderInviteEnterpriseService;
    protected final ProjectService projectService;

    public SupplyBidSignupController(SupplyBidSignupService supplyBidSignupService,
                                     BidSectionService bidSectionService,
                                     TenderInviteEnterpriseService tenderInviteEnterpriseService,
                                     ProjectService projectService) {
        this.supplyBidSignupService = supplyBidSignupService;
        this.bidSectionService = bidSectionService;
        this.tenderInviteEnterpriseService = tenderInviteEnterpriseService;
        this.projectService = projectService;
    }

    /**
     * @param supplyBidSignup:
     * @Description: 查询供应商报名列表  跟产品确认 只有公开和需要报名的项目,并且已经发了公告才展示
     * @Author: zhongdl
     * @Date:2021/12/21 16:45
     * @return: {@link PageResult< SupplyBidSignupDTO> }
     **/
    @PostMapping("/supplyBidSignup/findSupplyBidSignupInfoList")
    public Message<PageResult<SupplyBidSignupDTO>> findSupplyBidSignupInfoList(@RequestBody SupplyBidSignupDTO supplyBidSignup) {
        PageResult<SupplyBidSignupDTO> supplyBidSignupDtoList = supplyBidSignupService.findSupplyBidSignupInfoList(supplyBidSignup);
        return MsgUtil.success(supplyBidSignupDtoList);
    }

    /**
     * 根据标段id查询投标人报名信息
     *
     * @param sectionId 标段Id
     * @param supplyId  供应商Id
     * @return
     */
    @GetMapping("/supplyBidSignup/findSupplyBidSignupInfoBySectionId")
    public Message<SupplyBidSignupDTO> findSupplyBidSignupInfoBySectionId(@RequestParam(value = "sectionId") Long sectionId, @RequestParam(value = "supplyId") Long supplyId) {
        //查询该标段的报名信息
        QueryWrapper<SupplyBidSignup> supplyBidSignupQueryWrapper = new QueryWrapper<>();
        supplyBidSignupQueryWrapper.select("project_id,contact_name,mobile,tel,email,note,bid_doc_file")
                .lambda().eq(SupplyBidSignup::getSectionId, sectionId).eq(SupplyBidSignup::getCreateId, supplyId).last("limit 1");
        SupplyBidSignup supplyBidSignup = supplyBidSignupService.getOne(supplyBidSignupQueryWrapper);
        if (supplyBidSignup == null) {
            supplyBidSignup = new SupplyBidSignup();
        }

        /*if (StrUtil.isEmpty(supplyBidSignup.getContactName()) && StrUtil.isEmpty(supplyBidSignup.getMobile())){
              //联系人/联系人手机
            supplyBidSignup.setContactName(organizeExtendInfo.getContactName());
            supplyBidSignup.setMobile(organizeExtendInfo.getTel());
        }
        if (supplyBidSignup.getProjectId() == null){
            BidSection bidSection = bidSectionService.getById(sectionId);
            supplyBidSignup.setProjectId(bidSection.getProjectId());
        }*/
        SupplyBidSignupDTO supplyBidSignupDto = supplyBidSignup.to(SupplyBidSignupDTO.class);
        //根据项目id查询标段的报名信息
        // TODO: 2021-11-5  这里为什么要根据项目ID查询？？？？
        /*List<SupplyBidSignupDTO> supplyBidSignupDtoList = supplyBidSignupService.findBidSectionSignUpInfo(supplyBidSignupDto.getProjectId());
        supplyBidSignupDto.setSupplyBidSignupList(supplyBidSignupDtoList);
        supplyBidSignupDto.setUnitName(StrUtil.isEmpty(organizeExtendInfo.getOrgName()) ? "单位名称" : organizeExtendInfo.getOrgName());//设置单位名称*/
        return MsgUtil.success(supplyBidSignupDto);
    }

    /**
     * 根据标段集合查询报名成功的投标人信息
     *
     * @author yuezheng
     * @param sectionIdList
     * @return Message<SupplyBidSignupDTO>
     * @date 2022/4/16 3:34 PM
     */
    @PostMapping("/supplyBidSignup/findSupplyBidSignupInfoBySectionIdList")
    public Message<List<SupplyBidSignup>> findSupplyBidSignupInfoBySectionIdList(@RequestBody List<Long> sectionIdList) {
        QueryWrapper<SupplyBidSignup> queryWrapper = new QueryWrapper<>();
        // 2022年5月17日测试提bug标书发售-发短信-需求要求只要报名过的就发短信，不区分状态，目前只给审核通过的发了短信
        queryWrapper.lambda().select(SupplyBidSignup::getId,SupplyBidSignup::getBidderId).in(SupplyBidSignup::getSectionId,sectionIdList);
//        queryWrapper.eq(SupplyBidSignup::getSignupStatus,1);
        List<SupplyBidSignup> list = this.supplyBidSignupService.list(queryWrapper);
        return MsgUtil.success(list);
    }

    /**
     * @param supplyBidSignup: 报名的对象
     * @param clientIpAddress: 客户端ip
     * @Description: 保存投标人报名信息
     * @Author: zhongdl
     * @Date:2021/12/6 9:50
     * @return: {@link org.fzzn.core.model.msg.Message }
     **/
    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/supplyBidSignup/saveSupplyBidSignupInfo")
    public Message saveSupplyBidSignupInfo(@RequestBody SupplyBidSignupDTO supplyBidSignup, String clientIpAddress) {
        String msg = supplyBidSignup.paramsValid();
        if (StringUtils.isNotBlank(msg)) {
            return MsgUtil.fail(msg);
        }
        //判断当前企业是否已有其他人报名
        SupplyBidSignup orgSupplyBidSignupInfo = supplyBidSignupService.getOrgSupplyBidSignupInfo(supplyBidSignup.getOrgId(),null, supplyBidSignup.getSectionId());
        //判断当前登录人与 已报名投标人是否一致
        if(!ObjectUtils.isEmpty(orgSupplyBidSignupInfo) && !orgSupplyBidSignupInfo.getBidderId().equals(supplyBidSignup.getBidderId())){
            return MsgUtil.fail("当前标段已有本公司其他员工进行报名，无法再次报名！");
        }
        //判断是否有报名信息（重新报名）
        SupplyBidSignup signup = supplyBidSignupService.getOrgSupplyBidSignupInfo(supplyBidSignup.getOrgId(), supplyBidSignup.getBidderId(), supplyBidSignup.getSectionId());
        if (signup != null && signup.getId() != null) {
            supplyBidSignup.setId(signup.getId());
            supplyBidSignupService.updateById(supplyBidSignup);
        } else {
            supplyBidSignupService.save(supplyBidSignup);

        }
        return MsgUtil.success();
    }

    /**
     * 保存投标确认函
     *
     * @param supplyBidSignup
     * @return
     */
    @PutMapping("/supplyBidSignup/saveConfirmSupplyBidSignupInfo")
    public Message saveConfirmSupplyBidSignupInfo(@RequestBody SupplyBidSignupDTO supplyBidSignup) {
        String msg = supplyBidSignup.paramsConfirmValid();
        if (StringUtils.isNotBlank(msg)) {
            return MsgUtil.fail(msg);
        }
        //先删除后加
        QueryWrapper<SupplyBidSignup> supplyBidSignupQueryWrapper = new QueryWrapper<>();
        supplyBidSignupQueryWrapper.lambda().eq(SupplyBidSignup::getSectionId, supplyBidSignup.getSectionId());
        supplyBidSignupService.remove(supplyBidSignupQueryWrapper);
        //转换要保存的信息
        BidSection bidSection = bidSectionService.getById(supplyBidSignup.getSectionId());
        supplyBidSignup.setProjectId(bidSection.getProjectId());
//        supplyBidSignup.setId(RandomUtil.uuId());
//        if (StrUtil.isEmpty(supplyBidSignup.getSupplyId())){
//            supplyBidSignup.setSupplyId(userProvider.get().getOrganizeId());
//        }
//        supplyBidSignup.setIpAddress(CommonUtil.getClientIpAddress(request));
//        supplyBidSignupService.save(supplyBidSignup);
//        tenderInviteEnterpriseService.updateInviteStatus(supplyBidSignup.getInviteId(), InviteStatusEnum.CONFIRM_PARTICIPATION.getCode());
        return MsgUtil.success();
    }

    /**
     * 根据标段id查询投标确认函详情
     *
     * @param sectionId 标段id
     * @return
     */
    @GetMapping("/supplyBidSignup/findConfirmSupplyBidSignupDetails")
    public Message<SupplyBidSignup> findConfirmSupplyBidSignupDetails(@RequestParam(value = "sectionId") Long sectionId, @RequestParam(value = "supplyId") Long supplyId) {
        QueryWrapper<SupplyBidSignup> supplyBidSignupQueryWrapper = new QueryWrapper<>();
        supplyBidSignupQueryWrapper.select("confirm_message,note,bid_doc_file,tel").lambda()
                .eq(SupplyBidSignup::getSectionId, sectionId)
                .eq(SupplyBidSignup::getOrgId, supplyId);
        SupplyBidSignup supplyBidSignup = supplyBidSignupService.getOne(supplyBidSignupQueryWrapper);
        return MsgUtil.success(supplyBidSignup);
    }

    /**
     * 查询我的项目信息
     *
     * @param supplyBidSignup
     * @return
     */
    @PostMapping("/supplyBidSignup/findMyProjectList")
    public Message<PageResult<SupplyBidSignupDTO>> findMyProjectList(@RequestBody SupplyBidSignupDTO supplyBidSignup) {
        Page<SupplyBidSignupDTO> supplyBidSignupDtoList = supplyBidSignupService.findMyProjectList(supplyBidSignup);
        return MsgUtil.success(PageResult.get(supplyBidSignupDtoList));
    }

    /**
     * 根据标段id查询当前标段下的报名数量
     *
     * @param supplyBidSignupDTO
     * @return
     */
    @PostMapping("/supplyBidSignup/findSectionSignUpCount")
    public Message findSectionSignUpCount(@RequestBody SupplyBidSignupDTO supplyBidSignupDTO) {
        if (null != supplyBidSignupDTO.getSectionId()) {
            //详情页根据标段Id统计报名数量
            SupplyBidSignupDTO supplyBidSignup = supplyBidSignupService.getSignupCountBySectionId(supplyBidSignupDTO.getSectionId());
            return MsgUtil.success(supplyBidSignup);
        } else if (null != supplyBidSignupDTO.getProjectId()) {
            //列表页根据项目Id统计各个标段的数量
            //根据项目Id查询所有标段分页
            PageResult<SupplyBidSignupDTO> sectionPage = bidSectionService.pageSectionListByProjectId(supplyBidSignupDTO.pages(), supplyBidSignupDTO.getProjectId());
            for (SupplyBidSignupDTO supplyBidSignup : sectionPage.getRecords()) {
                SupplyBidSignupDTO signupDTO = supplyBidSignupService.getSignupCountBySectionId(supplyBidSignup.getSectionId());
                signupDTO.to(supplyBidSignup);
            }
            return MsgUtil.success(sectionPage);
        }
        return MsgUtil.fail(MsgEnum.INCORRECT_PARAM.msg());
    }

    /**
     * @param supplyBidSignupDTO:
     * @Description: 招标人查询标段下的所有报名信息
     * @Author: zhongdl
     * @Date:2021/12/21 14:38
     * @return: {@link List<SupplyBidSignupDTO> }
     **/
    @PostMapping("/supplyBidSignup/getSectionSignupList")
    public Message<List<SupplyBidSignupDTO>> getSectionSignupList(@RequestBody SupplyBidSignupDTO supplyBidSignupDTO) {
        List<SupplyBidSignupDTO> supplyBidSignupList = supplyBidSignupService.getSectionSigupList(supplyBidSignupDTO);
        return MsgUtil.success(supplyBidSignupList);
    }

    /**
     * @param supplyBidSignupDTO:
     * @Description: 招标人查询标段下的所有报名信息
     * @Author: zhongdl
     * @Date:2021/12/21 14:38
     * @return: {@link List< SupplyBidSignupDTO> }
     **/
    @PostMapping("/supplyBidSignup/pageSectionSignup")
    public Message<PageResult<SupplyBidSignupDTO>> pageSectionSignup(@RequestBody SupplyBidSignupDTO supplyBidSignupDTO) {
        PageResult<SupplyBidSignupDTO> supplyBidSignupDTOPageResult = supplyBidSignupService.pageSectionSignup(supplyBidSignupDTO);
        return MsgUtil.success(supplyBidSignupDTOPageResult);
    }

    /**
     * 导出投标人报名列表信息
     *
     * @param supplyBidSignup
     * @return
     * @author zhaojk
     */
    @PostMapping("/supplyBidSignup/listSectionSignup")
    public Message<List<JSONObject>> listSectionSignup(@RequestBody SupplyBidSignupDTO supplyBidSignup) {
        List<JSONObject> list = supplyBidSignupService.listSectionSignup(supplyBidSignup);
        return MsgUtil.success(list);
    }

    /**
     * 根据标段Id查询的未审核具体报名信息
     *
     * @param supplyBidSignupDTO
     * @return
     */
    @PostMapping("/supplyBidSignup/findSectionSignUpList")
    public Message<SupplyBidSignupDTO> findSectionSignUpList(@RequestBody SupplyBidSignupDTO supplyBidSignupDTO) {
        SupplyBidSignupDTO supplyBidSignupDto = new SupplyBidSignupDTO();
        BidSection bidSection = bidSectionService.getById(supplyBidSignupDTO.getSectionId());
        if (bidSection == null) {
            return MsgUtil.fail("标段信息不存在");
        }
        supplyBidSignupDto.setSectionName(bidSection.getSectionName());
        supplyBidSignupDto.setSectionCode(bidSection.getSectionCode());
        AbstractProject project = projectService.getByPrimaryKey(bidSection.getProjectId());
        if (project == null) {
            return MsgUtil.fail("项目不存在");
        }
        supplyBidSignupDto.setProjectCode(project.getProjectCode());
        supplyBidSignupDto.setProjectName(project.getProjectName());
        //查询已报名的信息，供审核使用
        QueryWrapper<SupplyBidSignup> supplyBidSignupQueryWrapper = new QueryWrapper<>();
        supplyBidSignupQueryWrapper.lambda()
                .eq(SupplyBidSignup::getSectionId, supplyBidSignupDTO.getSectionId())
                .eq(SupplyBidSignup::getSignupStatus, SignupStatusEnum.REG_PROGRESS.getCode());
        List<SupplyBidSignup> list = supplyBidSignupService.list(supplyBidSignupQueryWrapper);
        List<SupplyBidSignupDTO> supplyBidSignupDtoList = SupplyBidSignupDTO.changeSupplyBidSignupDto(list);
        //设置单位名称  报名状态 保证金
        for (SupplyBidSignupDTO bidSignupDto : supplyBidSignupDtoList) {
//            OrganizeExtendInfo organizeExtendInfo = organizeExtendInfoService.findByOrgId(bidSignupDto.getSupplyId());
//            bidSignupDto.setUnitName(organizeExtendInfo.getOrgName());
            bidSignupDto.setSignupStatusName(Enums.nameOf(SignupStatusEnum.class, bidSignupDto.getSignupStatus()));
            bidSignupDto.setBondFlagName(Enums.nameOf(LogicEnum.class, bidSignupDto.getBondFlag()));
        }
        supplyBidSignupDto.setSupplyBidSignupList(supplyBidSignupDtoList);
        return MsgUtil.success(supplyBidSignupDto);
    }

    /**
     * 根据主键Id查询报名信息详情
     *
     * @param supplyBidSignup
     * @return
     */
    @PostMapping("/supplyBidSignup/getSupplySignupInfo")
    public Message<SupplyBidSignupDTO> getSupplySignupInfo(@RequestBody SupplyBidSignup supplyBidSignup) {
        if (null == supplyBidSignup.getId()) {
            // 无参数时返回空对象, 避免页面提示无效信息
            return MsgUtil.success();
        }
        return MsgUtil.success(supplyBidSignupService.getSupplySignupInfo(supplyBidSignup.getId()));
    }

    /**
     * 审核通过
     *
     * @param supplyBidSignup
     * @return
     */
    @PostMapping("/supplyBidSignup/passExamine")
    public Message<Boolean> passExamine(@RequestBody SupplyBidSignup supplyBidSignup) {
        if (null == supplyBidSignup.getId()) {
            return MsgUtil.fail(MsgEnum.INCORRECT_PARAM.msg());
        }
        supplyBidSignup.setSignupStatus(SignupStatusEnum.REGISTERED.getCode());
        Boolean result = supplyBidSignupService.signupExamine(supplyBidSignup);
        return MsgUtil.msg(result);
    }

    /**
     * 审核不通过
     *
     * @param supplyBidSignup
     * @return
     */
    @PostMapping("/supplyBidSignup/failExamine")
    public Message<Boolean> failExamine(@RequestBody SupplyBidSignup supplyBidSignup) {
        if (null == supplyBidSignup.getId()) {
            return MsgUtil.fail(MsgEnum.INCORRECT_PARAM.msg());
        }
        supplyBidSignup.setSignupStatus(SignupStatusEnum.REG_FAILED.getCode());
        Boolean result = supplyBidSignupService.signupExamine(supplyBidSignup);
        return MsgUtil.msg(result);
    }

}
